const base_url = "http://audio.lolikon.cc/stream";
let steamStr = "";

export function aiFetch({
  method,
  data,
  url,
  onmessage = () => {},
  onerror = () => {},
  ondone = () => {}
}) {
  fetch(`${base_url}?text=${data.text}`, {
    method,
    headers: {
      "Content-Type": "text/event-stream"
    },
    data: JSON.stringify(data)
  })
    .then(function (res) {
      const reader = res.body.getReader();
      const decoder = new TextDecoder();
      function read() {
        reader
          .read()
          .then(({ done, value }) => {
            if (done) {
              ondone();
              return;
            }
            steamStr += decoder.decode(value);
            if (steamStr.includes("\n\n")) {
              const arr = steamStr.split("\n\n");
              try {
                while (arr.length > 1) {
                  const current = arr.shift().replace("data:", "");
                  // console.log("success", current.indexOf("phoneme"));
                  onmessage(current);
                  // return
                }
              } catch (err) {
                console.log(current);
                console.log(err);
              }
              steamStr = arr[0];
            }
            // console.log("value", decoder.decode(value));
            // onmessage(steamStr);
            read();
          })

          .catch((error) => {
            onerror(error);
          });
      }
      read();
    })
    .then(function (data) {
      // console.log(data)
    });
}

export function aiGenerate({
  text = "",
  onmessage = () => {},
  ondone = () => {},
  onerror = () => {}
}) {
  aiFetch({
    url: "/plugin/ai/text",
    method: "get",
    data: { text, stream: true },
    onmessage: (text) => {
      onmessage(text);
    },
    ondone: () => {
      ondone();
    }
  });
}
